package com.rb.demo

import android.content.IntentFilter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initClickListener()
    }

    private var broadcastReceiver: DynamicRegisterBoardCast? = null
    private fun initClickListener() {
        btn_rb_binder.setOnClickListener { dynamicRegister() }
        btn_rb_un_binder.setOnClickListener { unBinderRegister() }
        btn_dynamic_register.setOnClickListener {
            if (null == broadcastReceiver) {
                broadcastReceiver = DynamicRegisterBoardCast()
                val intentFilter = IntentFilter(DynamicRegisterBoardCast.ACTION)
                registerReceiver(broadcastReceiver, intentFilter)
                Toast.makeText(this, "动态注册成功", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(this, "已注册", Toast.LENGTH_LONG).show()
            }
        }
    }

    var receiver: MyBroadcast2? = null
    private fun dynamicRegister() {
        if (null == receiver) {
            //创建receiver对象
            receiver = MyBroadcast2()
            //创建过滤器对象
            val filter = IntentFilter("www.ssjywm.com.action")
            //注册receiver
            registerReceiver(receiver, filter)
            Toast.makeText(this, "动态注册广播接收器", Toast.LENGTH_LONG).show()
        } else {
            Toast.makeText(this, "已注册广播接收器", Toast.LENGTH_LONG).show()
        }
    }

    private fun unBinderRegister() {
        if (null != receiver) {
            unregisterReceiver(receiver)
            receiver = null
            Toast.makeText(this, "解绑广播接收器", Toast.LENGTH_LONG).show()
        } else {
            Toast.makeText(this, "未注册广播接收器", Toast.LENGTH_LONG).show()
        }
    }

    override fun onDestroy() {
        if (null != receiver) {
            unregisterReceiver(receiver)
            receiver = null
        }
        super.onDestroy()
    }
}
